#include "HttpServer.h"
#include "DetectionInfer.h"



RestfulClient::RestfulClient(const utility::string_t& url)
        : m_client(url) {

}

void RestfulClient::sendAsyncPostRequest(const utility::string_t& clientId, 
					 const utility::string_t& base64Image,
					 const double objThre,
					 const http_request &request) {

       // 异步方式处理图像数据
       pplx::create_task([this, clientId, base64Image, objThre, request]() {

            // 处理图像数据
            std::vector<uint8_t> imageData = utility::conversions::from_base64(base64Image);
	    try {
        	imageData = utility::conversions::from_base64(base64Image);
            } catch (...) {
                std::cerr << "解码Base64字符串失败。" << std::endl;
        	return -1;
    	    }

            // 保存图像文件
            cv::Mat image = cv::imdecode(imageData, cv::IMREAD_COLOR);
            cv::imwrite("image_" + utility::conversions::to_utf8string(clientId) + ".jpg", image);

	    DetectionInfer infer;
	    infer.E2eInfer(imageData, objThre);

	    http_response response;
    	    response.headers().add(U("Content-Type"), U("application/json"));
    	    response.set_status_code(status_codes::OK);
    	    request.reply(response);
        });
}

HttpServer::HttpServer(const utility::string_t& url) 
	: m_listener(url) {

    if (m_pdetect == nullptr) {
	m_pdetect = std::make_shared<DetectionInfer>();
    }

    m_listener.support(methods::POST, std::bind(&HttpServer::handle_post, this, std::placeholders::_1));
    m_listener.support(methods::GET, std::bind(&HttpServer::handle_get, this, std::placeholders::_1));
}

void HttpServer::start() {
    m_listener.open().wait();
    // std::cout << "Server started at: " << m_listener.uri().to_string() << std::endl;
}

void HttpServer::stop() {
    m_listener.close().wait();
}

void HttpServer::handle_post(http_request request) {

   // 获取客户端发来的数据
   json::value body = request.extract_json().get();

   // 输出body内容
   const json::object& bodyObject = body.as_object();
#if 0
   for (const auto& kvPair : bodyObject) {
       const std::string fieldName = utility::conversions::to_utf8string(kvPair.first);
       const std::string fieldValue = utility::conversions::to_utf8string(kvPair.second.serialize());
       //std::cout << fieldName << ": " << fieldValue << std::endl;
    }
    utility::string_t clientId = body["clientId"].as_string();
#endif
    utility::string_t base64Image = body["image"].as_string();
    double objThreshold = body["threshold"].as_double(); 
    // 异步方式处理图像数据
    //RestfulClient client(U(SERVER_URL));
    //client.sendAsyncPostRequest(clientId, base64Image, objThreshold, request);
    
    // 处理图像数据, 写到队列t以及线程中，提高性能
    std::vector<uint8_t> imageData = utility::conversions::from_base64(base64Image);
    try {
        imageData = utility::conversions::from_base64(base64Image);
    } catch (...) {
        std::cerr << "解码Base64字符串失败。" << std::endl;
    }

#if DRAW_IMAGE
    // 保存图像文件
    cv::Mat image = cv::imdecode(imageData, cv::IMREAD_COLOR);
    cv::imwrite("image_" + utility::conversions::to_utf8string(clientId) + ".jpg", image);
#endif

    // DetectionInfer infer;
    std::string jsonStr = m_pdetect->E2eInfer(imageData, objThreshold);

    // 返回初始响应给客户端
    http_response response;
    response.headers().add(U("Content-Type"), U("application/json"));
    response.set_status_code(status_codes::OK);
    response.set_body(jsonStr);
    request.reply(response);
}

void HttpServer::handle_get(http_request request) {

    utility::string_t clientId = request.relative_uri().path();

    // 构建返回的JSON数据
    //json::value jsonResponse;
    //jsonResponse["clientId"] = json::value::string(utility::conversions::to_string_t(clientId));

    // 返回数据给客户端
    http_response response;
    response.headers().add(U("Content-Type"), U("application/json"));
    response.set_status_code(status_codes::OK);

    request.reply(response);
}

